package util;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import pageModel.User;

public class ShiroUtil {
    /**
     * 从凭证组中获取当前用户，仅获取第一个realm中的第一个对象
     *
     * @param subject shiro subject
     * @return User
     */
    public static User getUserByPrincipals(Subject subject) {
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        User user = (User) subject.getPrincipals().fromRealm(realmName).iterator().next();
        return user;
    }

    /**
     * 使用principals和realm获取放到principalCollection中的User对象
     *
     * @param principals 凭证组
     * @param realmName  realmName
     * @return User
     */
    public static User getUserByPrincipalsRealmName(PrincipalCollection principals, String realmName) {
        User user = (User) principals.fromRealm(realmName).iterator().next();
        return user;
    }
    
    /**
	 * 获取当前用户session
	 * @return session
	 */
	public static Session getSession(){
		Session session =SecurityUtils.getSubject().getSession();
		return session;
	}
	
	/**
	 * 获取当前用户对象
	 * @return user
	 */
	public static User getCurrentUser(){
		Session session =SecurityUtils.getSubject().getSession();
		if(null!=session){
			return (User) session.getAttribute("user");
		}else{
			return null;
		}
		
	}
}